<?php
/**
 * Created by PhpStorm.
 * User: hedx
 * Date: 2016/3/29
 * Time: 11:24
 */

namespace common\mq;

use Yii;
use yii\base\Exception;

/**
 * 消息服务工厂方法：负责获取消息服务具体实例并返回其接口类型
 *
 * Class MessageService
 * @package common\mq
 */
class MessageServiceFactory
{
    /**
     * @var MessageServiceInterface 消息服务接口实例
     */
    private static $mqInstance;

    /**
     * 获取消息服务的具体实例
     *
     * @return MessageServiceInterface
     * @throws \yii\base\Exception
     */
    public static function getMessageService()
    {
        if (self::$mqInstance == null) {
            $mq = Yii::$app->get('mq');
            if($mq instanceof MessageServiceInterface){
                self::$mqInstance = $mq;
            } else {
                throw new Exception("No valid message service instance which implements MessageServiceInterface!");
            }
        }
        return self::$mqInstance;
    }

    /**
     * 根据队列名获取某个队列
     *
     * @param $queueName
     * @return mixed
     */
    public static function getMessageQueue($queueName){
        return self::getMessageService()->getClient()->getQueueRef($queueName);
    }

    /**
     * 根据主题名获取某个主题
     *
     * @param $topicName
     * @return mixed
     */
    public static function getMessageTopic($topicName){
        return self::getMessageService()->getClient()->getTopicRef($topicName);
    }


}